<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';
import type { Dayjs } from 'dayjs';

import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CustomerForm } from '#/api/hm/customer/model';

import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { getVxePopupContainer } from '@vben/utils';

import { MinusCircleTwoTone } from '@ant-design/icons-vue';
import { Popconfirm, Select, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { customerUpdateFamily, familyAllocatedList } from '#/api/hm/customer';
import { familyUpdate } from '#/api/hm/family';
import { getDictOptions } from '#/utils/dict';

import { columns, querySchema } from './data';
import familyAssignDrawer from './family-assign-drawer.vue';

const route = useRoute();
const familyId = route.params.familyId as string;

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  editConfig: {
    trigger: 'click',
    mode: 'cell',
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await familyAllocatedList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          familyId,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'customerId',
  },
  id: 'family-assign-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [FamilyAssignDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: familyAssignDrawer,
});

function handleAdd() {
  drawerApi.setData({ id: familyId });
  drawerApi.open();
}

/**
 * 取消授权 一条记录
 */
async function handleAuthCancel(record: CustomerForm) {
  const params = {
    customerId:
      typeof Number(record.customerId) === 'number'
        ? record.customerId
        : undefined,
    eventAction: 'TC',
    customerName:
      typeof Number(record.customerId) === 'number'
        ? undefined
        : record.customerName,
    familyId,
  };

  await customerUpdateFamily(params);
  await tableApi.query();
}

interface User {
  userName: string | undefined;
  userType: string | undefined;
  userBirth: Dayjs | undefined;
  id: number;
}
const formRef = ref<FormInstance>();
const dynamicValidateForm = reactive<{ familyId: string; users: User[] }>({
  users: [],
  familyId,
});
const removeUser = (item: User) => {
  const index = dynamicValidateForm.users.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.users.splice(index, 1);
  }
};
const addUser = () => {
  dynamicValidateForm.users.push({
    userName: '',
    userType: undefined,
    userBirth: undefined,
    id: Date.now(),
  });
};
const onFinish = (values) => {
  console.log('Received values of form:', values);
  console.log('dynamicValidateForm.users:', dynamicValidateForm.users);
};
const visible = ref(false);
const onOk = () => {
  formRef.value
    .validateFields()
    .then(async (values) => {
      // 将Values转换为Json字符串
      const jsonString = JSON.stringify(values.users);
      const params = {
        familyId,
        threePerson: jsonString,
      };
      await familyUpdate(params).then((res) => {
        console.log('修改三代信息成功', res);
      });
      tableApi.query();
      visible.value = false;
      formRef.value.resetFields();
    })
    .catch((error) => {
      console.log('Validate Failed:', error);
    });
};
const onCancel = () => {
  visible.value = false;
  formRef.value.resetFields();
  dynamicValidateForm.users = [];
};

const filteredFamilyTypeOptions = computed(() => {
  return getDictOptions(DictEnum.SYS_FAMILY_TYPE).filter((opt) =>
    ['SN', 'SZ', 'WSN', 'WSZ'].includes(opt.value as string),
  );
});
</script>
<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="已分配的客户列表">
      <template #toolbar-tools>
        <Space>
          <a-button type="primary" @click="handleAdd">
            {{ $t('pages.common.add') }}
          </a-button>
          <a-button type="primary" @click="visible = true">
            新增三代信息
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Popconfirm
          :get-popup-container="getVxePopupContainer"
          :title="`是否取消分配[${row.customerName}?]`"
          placement="left"
          @confirm="handleAuthCancel(row)"
        >
          <ghost-button danger @click.stop=""> 退出家庭组 </ghost-button>
        </Popconfirm>
      </template>
    </BasicTable>
    <FamilyAssignDrawer @reload="tableApi.query()" />
    <!-- 新增三代信息 -->
    <a-modal
      v-model:open="visible"
      title="新增三代信息"
      ok-text="新增"
      cancel-text="取消"
      @ok="onOk"
      @cancel="onCancel"
    >
      <a-form
        ref="formRef"
        name="dynamic_form_nest_item"
        :model="dynamicValidateForm"
        @finish="onFinish"
      >
        <a-space
          v-for="(user, index) in dynamicValidateForm.users"
          :key="user.id"
          style="display: flex; margin-bottom: 8px"
          align="baseline"
        >
          <a-form-item
            :name="['users', index, 'userName']"
            :rules="{
              required: true,
              message: '请输入姓名',
            }"
          >
            <a-input v-model:value="user.userName" placeholder="用户姓名" />
          </a-form-item>
          <a-form-item
            :name="['users', index, 'userType']"
            :rules="{
              required: true,
              message: '请选择用户类型',
            }"
          >
            <Select
              v-model:value="user.userType"
              placeholder="请选择用户类型"
              style="width: 130px"
              :options="filteredFamilyTypeOptions"
            />
          </a-form-item>
          <a-form-item
            :name="['users', index, 'userBirth']"
            :rules="{
              required: true,
              message: '请选择用户生日',
            }"
          >
            <a-date-picker
              v-model:value="user.userBirth"
              placeholder="生日"
              format="YYYY/MM/DD"
              value-format="YYYY/MM/DD"
            />
          </a-form-item>
          <MinusCircleTwoTone
            two-one-color="#eb2f34"
            @click="removeUser(user)"
          />
        </a-space>
        <a-form-item>
          <a-button type="dashed" block @click="addUser">
            <PlusOutlined />
            添加三代信息
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </Page>
</template>

<style scoped>
.collection-create-form_last-form-item {
  margin-bottom: 0;
}
</style>
